package com.hxgis.oc.ws;

import lombok.extern.slf4j.Slf4j;

import javax.websocket.Session;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class WSClient {
    static WSClient singletonInstance = new WSClient();

    private WSClient(){

    }

    public static WSClient getInstance() {
        return singletonInstance;
    }

    private static AtomicInteger onlineNum = new AtomicInteger();
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    public void sendMessage(Session session, String message) throws IOException {
        if(session != null){
            synchronized (session) {
                session.getBasicRemote().sendText(message);
            }
        }
    }

    public void sendInfo(String userName, String message){
        Session session = sessionPools.get(userName);
        try {
            sendMessage(session, message);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void addClient(String userName, Session session) {
        sessionPools.put(userName, session);
        addOnlineCount();
        try {
            sendMessage(session, "connected to OCServer WS.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void onMessage(String message) {
        log.debug(message);
    }

    public void closeClient(String userName) {
        sessionPools.remove(userName);
        subOnlineCount();
    }

    public static void addOnlineCount(){
        onlineNum.incrementAndGet();
    }

    public static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }
}
